<?php

/**
 * 尚品双流仓SDK
 * @author chenyun
 */

namespace App\Service\VendorClient\Shopshuangliu;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;
use Service\AppService\IdService;

class ShopshuangliuApiClient
{
    private $account  = 'shopshuangliu';
    protected $config;
    protected $RouteMap = [
        'createOrder'          => 'declare.orderPush',
        'cancelOrder'          => 'declare.afterPush',
    ];
    /**
     * 初始参数
     * @param obj $collection
     */
    public function __construct( $apiBody = [] ) 
    {
        $this->config = $apiBody;
    }
    
    /**
     * 创建订单
     */
    public function createOrder( $params = [] ) 
    {   
        ini_set('serialize_precision', 16);
        
        if( empty($params['supplierOrder']) || empty($params['orderGoods']) || empty($params['order']) || empty($params['binfo']) ) {
            return Normal::returnCode(Normal::FAIL,"except param supplierOrder or orderGoods or order or binfo");
        }
        //组装订单参数
        $orderInfo = $params['supplierOrder'];
        $order     = $params['order'];
        $binfo     = $params['binfo'];
        //运费
        $deliver_money  = $orderInfo['deliver_money'];
        //商品下单组
        $goods = [];
        $productAmt = $TaxAmt = 0 ;
        foreach ($params['orderGoods'] as $key => $item )
        {
            //卖价
            $price              = $item['price'];
            //商品购买规格数量
            $spec_num           = $item['spec_num'];
            //商品购买数量(下单数量 X 起售数量)
            $quantity           = $item['quantity'];
            //实际购买数量
            $buyAcount          = $spec_num * $quantity ;

            //商品单价包含税金
            if( $key == 0 ) {
                $singleDeliveryMoney = bcdiv((string)$deliver_money,(string)$quantity,3);
                $singleDeliveryMoney = bcmul((string)$singleDeliveryMoney,(string)100,1);
                $singleDeliveryMoney = bcdiv((string)ceil($singleDeliveryMoney), (string)100,2);
                $price               = bcadd((string)$price, (string)$singleDeliveryMoney,2);
            }
            
            //单个商品价格
            $singleGoodsPrice   = bcdiv((string)$price, (string)$spec_num,3);
            $singleGoodsPrice   = ceil(bcmul((string)$singleGoodsPrice,(string)'100',1));
            $singleGoodsPrice   = bcdiv((string)$singleGoodsPrice,'100',2);
            $totalGoods         = bcmul((string)$singleGoodsPrice,(string)$buyAcount,2);
            
            //商品组
            $goods[] = [
                'goodsIndex'    => $key+1,
                'ebpGoodsNo'    => $item['supplier_skucode'],
                'ebpGoodsName'  => $item["goods_name"],
                'ebpPrice'      => $singleGoodsPrice,
                'ebpQty'        => $buyAcount,
            ];

            $productAmt = bcadd((string)$productAmt,(string)$totalGoods,2);
        }
        //实际下单金额
        $real_total_money   = $orderInfo['real_total_money'];
        
        //订单总金额 = 含税商品总金额 + 运费 - 优惠金额
        $ActualPaidAmt      = bcadd((string)$productAmt,(string)$TaxAmt,2);
        //优惠金额
        $discount_money     = bcsub((string)$ActualPaidAmt,$real_total_money,2);
        
        //下单支付的时候支付信息
        $apply_extends  = @json_decode($orderInfo['apply_extends'],true);
        
        //支付时间
        $payTime        = empty($order['payTime']) ? $orderInfo['pay_time'] :$order['payTime'];
        //支付时间
        $pay_time       = $payTime ? $payTime : time();
        $pay_time       = date('Y-m-d H:i:s',$pay_time);
        
        
        //支付流水号
        $pay_sn         = $order['paySerial']??$orderInfo['pay_sn'];
        $deduction      = 0.00;
        
        //获取上游供应商支付方式路由
        $payCommanyCode = $apply_extends['payCommanyCode'] ?? '';
        $PayCompanyCode = $order['payCommanyCode'] ? $order['payCommanyCode'] : $payCommanyCode;
        
        //电商平台信息
        $enterpriseNum = $apply_extends['enterpriseNum'] ?? '';
        $enterpriseName = $apply_extends['enterpriseName'] ?? '';
        $enterpriseNum = $order['enterpriseNum'] ? $order['enterpriseNum'] : $enterpriseNum;
        $enterpriseName = $order['enterpriseName'] ? $order['enterpriseName'] : $enterpriseName;
        
        //创建订单数据
        $data = [
            'platformOrderNo'       => $orderInfo['supplier_dsn'],
            'declareNo'             => $orderInfo['supplier_dsn'],
            'orderTime'             => date("Y-m-d H:i:s",$orderInfo['cd']),
            'payTime'               => $pay_time,
            'payTransactionId'      => $pay_sn,
            'ebpPayCode'            => $PayCompanyCode,
            'buyerRegNo'            => $orderInfo['buyer_phone'],
            'buyerIdNumber'         => $orderInfo['buyer_idcard'],
            'buyerName'             => $orderInfo['buyer_realname'],
            'buyerTelephone'        => $orderInfo['buyer_phone'],
            'consigneeProvince'     => $orderInfo['province'],
            'consigneeCity'         => $orderInfo['city'],
            'consigneeArea'         => $orderInfo['district'],
            'consigneeAddress'      => $orderInfo['province'].$orderInfo['city'].$orderInfo['district'].$orderInfo['receive_address'],
            'consignee'             => $orderInfo['receive_name'],
            'consigneeTelephone'    => $orderInfo['recveive_phone'],
            'freight'               => 0,
            'discount'              => $discount_money,
            'tax'                   => 0,
            'goodsValue'            => $productAmt,
            'payfee'                => (float)$real_total_money,
            'ebpCode'               => $enterpriseNum,
            'ebpName'               => $enterpriseName,
            'goodsList'             => $goods,
        ];
        $requestParam = [
            'method'    => 'createOrder',
            'data'      => $data
        ];
        $res= $this->execute($requestParam);
        return $res;
    }
   
    /**
     * 获取取消订单
     */
    public function cancelOrder( $params = [] ) 
    {
        if( empty($params['supplierOrder'])) {
            return Normal::returnCode(Normal::FAIL,"except param supplierOrder ");
        }
        //组装订单参数
        $orderInfo = $params['supplierOrder'];
        $data = [
            'platformOrderNo' => $orderInfo['supplier_dsn'],
        ];
        $requestParam = [
            'method'    => 'cancelOrder',
            'data'      => $data
        ];
        return $this->execute($requestParam);
    }
    
    /**
     * 加签
     * @param array $param
     */
    protected function getSign( array $param = [] )
    {
        //第一步：将参数（除去sign外）以字典序升序排序
        ksort($param);
        //第二步：拼接参数和参数值（key1value1key2value2........）得到原始字符串 str。
        $string="";
        foreach ($param as $k=>$v){
            $string.=$k.$v;
        }
        //第三步：收尾拼接秘钥
        $string = $this->config["appsecret"].$string.$this->config["appsecret"];
        //第四步：将得到的字符串，全部转为小写
        $string = strtolower($string);
        //第五步：将待签名字符串做MD5加密后放入请求参数 sign
        $string = md5($string);
        return $string;
    }
    
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )  
    { 
        if( empty($param['data']) ) {
            return Normal::returnCode(Normal::FAIL,"数据不能为空");
        }
        $method = $param['method'];
        $url = $this->config['baseurl'];
        $data = [
            'appkey'        => $this->config["appkey"],
            'bizcontent'    => json_encode($param["data"],JSON_UNESCAPED_UNICODE),
            'method'        => $this->RouteMap[$method],
            'timestamp'     => time(),
        ];
        $data["sign"] = $this->getSign($data);
        $parameter = [
            [
                'tag'       => $this->account.'_'.$method,
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => $data,
                'method'    => "post",
                'format'    => 'x-www-form-urlencoded',
                'header'    => [],
        
            ],
        ];
        $resTask = TaskWorker::instance()->addTask($parameter);
        $resTask = current($resTask);
        $res     = $resTask['response']['result'];
        $resHttp = json_decode($res,true);
        if( isset($resHttp['code']) && $resHttp['code'] =='0' ) {
            return Normal::returnCode(Normal::SUC,$resHttp['msg'],$resHttp);
        }
        $message = isset($resHttp['msg']) ? $resHttp['msg'] : '请求失败';
        return Normal::returnCode(Normal::FAIL,$message);
    }
}